#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#ifdef RVS_TEST

#include "rvs_socket.h"
#define MYPORT1	2001
#define MYPORT2	2002
#define	REPORT1	3001
#define	REPORT2	3002
#define	socket	rvs_socket
#define	close	rvs_close
#define	bind	rvs_bind
#define	sendto	rvs_sendto
#define	recvfrom	rvs_recvfrom
#define	select	rvs_select
#define listen  rvs_listen
#define accept  rvs_accept
static inline void rvs_perror(const char* text)
{
    fprintf( stdout, "%s : Error = %d\n", text, rvs_errno);
}
#define	perror	rvs_perror

#else

#define MYPORT1	3001
#define MYPORT2	3002
#define	REPORT1	2001
#define	REPORT2	2002

#endif

static int sock1=-1, sock2=-1;
static char buffer[2048];
static int cont = 1;
static int selflag = 0;

static int
thread_create (pthread_t *tid, void *(*func)(void *), void *arg, int size)
{
    pthread_attr_t  attr;

    if (size) {
        pthread_attr_init (&attr);
        pthread_attr_setstacksize (&attr, size);
    }
    return pthread_create (tid, size ? &attr : NULL, func, arg);
}

/*------------------------------------*
 * 受信スレッド
 *------------------------------------*/
static void* recv_thread(void *param)
{
    struct timeval tv, *tvp=(struct timeval*)param;


    while(cont) {
        fd_set readfds;
        struct sockaddr_in from;
        socklen_t fromlen = sizeof(from);
        int nfds=0;
        int nev;

        FD_ZERO(&readfds);
        FD_SET(sock1, &readfds);
        FD_SET(sock2, &readfds);
        nfds = (sock1>sock2)?(sock1+1):(sock2+1);
            
        selflag = 1;
	fprintf(stdout, " calling select %x %x == ", nfds, *(unsigned *)&readfds);

	tv.tv_sec = tvp->tv_sec;
	tv.tv_usec = tvp->tv_usec;

        nev = select (nfds, &readfds, NULL, NULL, &tv);
	fprintf(stdout, " select returned %x\n", nev);
        selflag = 0;
        if (nev < 0) {
            perror("select");
        } else if (nev == 0) {
            fprintf( stdout, "select: Timeout\n");
        } else {
            int i, len;
            int sock = sock1;
            fprintf( stdout, "select: return %d\n", nev);
            for ( i=0; i<2; i++, sock=sock2) {
                if (FD_ISSET(sock, &readfds)) {
                    if ((len = recvfrom(sock, buffer, 2048, 0,
                              (struct sockaddr*)&from, &fromlen)) < 0) {
                        perror("recvfrom");
                        break;
                    }
                    fprintf( stdout, "recvfrom(sock%d) %s:%d\n", i+1,
                           inet_ntoa(from.sin_addr), ntohs(from.sin_port));
                    fprintf( stdout, " - %.*s\n", len, buffer);
                }
            }
        }
    }

    return NULL;
}

static int myport1=MYPORT1, myport2=MYPORT2;

void usage(char* cmd)
{
#define USAGE   "\
[USAGE]\n\
    %s [-1 <myport1>][-2 <myport2>][-h]\n"

    fprintf(stdout, USAGE, cmd);
}

int main(int argc, char** argv)
{
    struct sockaddr_in sin1, sin2, remote;
    int len;
    char cmd[16];
    char *prog = argv[0];
    struct timeval tv = { 60, 000000 };
    pthread_t tid;

    for (argc--, argv++; argc>0; argc--, argv++) {
        if (**argv != '-') {
            usage(prog);
            exit(1);
        }
        switch (*(*argv+1)) {
        case '1':
            argc--; argv++;
            myport1 = atoi(*argv);
            break;
        case '2':
            argc--; argv++;
            myport2 = atoi(*argv);
            break;
        case 'w':
            argc--; argv++;
            {
                char* next = strchr(*argv, ':');
                if (next) {
                    *next++ = 0;
                    tv.tv_usec = atoi(next);
                }
                tv.tv_sec = atoi(*argv);
            }
            break;
        default:
            usage(prog);
            exit(1);
        }
    }

    fprintf (stdout, "===== %s Started: MyPort#1=%d, MyPort#2=%d =====\n",
            prog, myport1, myport2);

    sock1 = socket (AF_INET, SOCK_DGRAM, 0);
    if (sock1 < 0) {
        perror("socket");
        goto sockerr;
    }
    sock2 = socket (AF_INET, SOCK_DGRAM, 0);
    if (sock2 < 0) {
        perror("socket");
        goto sockerr;
    }

    memset (&sin1, 0, sizeof(sin1));
    memset (&sin2, 0, sizeof(sin2));
    memset (&remote, 0, sizeof(remote));
    remote.sin_family = sin2.sin_family = sin1.sin_family = AF_INET;
    sin2.sin_addr.s_addr = sin1.sin_addr.s_addr = INADDR_ANY;
    remote.sin_addr.s_addr = inet_addr("127.0.0.1");
    sin1.sin_port = htons(myport1);
    sin2.sin_port = htons(myport2);
    remote.sin_port = htons(REPORT1);

    if (bind (sock1, (struct sockaddr*)&sin1, sizeof(sin1)) < 0) {
        perror("bind");
        goto sockerr;
    }
    if (bind (sock2, (struct sockaddr*)&sin2, sizeof(sin2)) < 0) {
        perror("bind");
        goto sockerr;
    }

    if (thread_create(&tid, recv_thread, &tv, 0) < 0) {
      perror("thread_create");
        goto sockerr;
    }

    fprintf (stdout, "[s/r] > ");

    while (cont && fgets(cmd, 16, stdin)) {
        int sock;
        struct sockaddr *addr;
        socklen_t addrlen = sizeof(struct sockaddr_in);
    
        switch(cmd[0]) {
        case 's':
        case 'S':
            fprintf (stdout, "from (1)%d / (2)%d ? ", myport1, myport2);
            fgets (cmd, 16, stdin);
            if (cmd[0] == '1') {
                 sock = sock1;
            } else {
                 sock = sock2;
            }
            fprintf (stdout, "to port# > ");
            fgets (cmd, 16, stdin);
            remote.sin_port = htons(atoi(cmd));
            addr = (struct sockaddr*)&remote;
            fprintf (stdout, "sending data >> ");
            if (fgets (buffer, 2048, stdin)) {
                while(!selflag) usleep(10000);
                len = sendto (sock, buffer, strlen(buffer)-1, 0, addr, addrlen);
                if (len > 0) {
                    fprintf (stdout, "sendto %s:%d\n",
                        inet_ntoa(((struct sockaddr_in*)addr)->sin_addr),
                        ntohs(((struct sockaddr_in*)addr)->sin_port));
                    fprintf( stdout, " - %.*s\n", len, buffer);
                } else {
                    perror("sendto");
                }
            } else {
                cont = 0;
            }
            break;
        case 'q':
        case 'Q':
            cont=0;
            break;
        }
        fprintf (stdout, "[s/r] > ");
    }

    close(sock1);
    close(sock2);
    pthread_join(tid, NULL);

    return 0;

sockerr:
    if (sock1 >= 0) close(sock1);
    if (sock2 >= 0) close(sock2);
    exit(1);
}
